/*
 * Copyright 2014 Semidata. All rights reserved.
 */
package com.semidata.trp.report.sort;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author shewei@semidata.com, She Wei
 * 
 */
public class FileDataProvider implements DataProvider<String> {

	private BufferedReader reader;
	private String currentLine = null;
	private static int DEFAULT_BUFFER_SIZE = 1024 * 1024;

	public FileDataProvider(File file) {
		this(file, DEFAULT_BUFFER_SIZE);
	}

	public FileDataProvider(File file, int bufferSize) {
		if (file == null || !file.exists() || !file.canRead())
			throw new RuntimeException("bad file");

		try {
			reader = new BufferedReader(new InputStreamReader(
			        new FileInputStream(file)), bufferSize);
			getLine();
		} catch (Exception e) {
			throw new RuntimeException("bad file");
		}
	}
	
	private void getLine() {
		while (true) {
			try {
				currentLine = reader.readLine();
				if (currentLine == null || currentLine.indexOf('\t') != -1)
					break;
			} catch (IOException e) {
				currentLine = null;
				break;
			}
		}
		if (currentLine == null) {
			try {
	            reader.close();
            } catch (IOException e) {
	        }
		}
	}

	@Override
	public String peek() {
		return currentLine;
	}

	@Override
	public String poll() {

		if (currentLine == null)
			return null;

		String line = currentLine;
		getLine();
		return line;
	}

}
